/**
 *  Copyright(C) 2012-2013 Suntec(Shanghai) Software Co., Ltd.
 *  All Right Reserved.
 */
package com.cugbmao.lucene;

import junit.framework.TestCase;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

/**
 * Descriptions
 * 
 * @version 2013年5月28日
 * @author Suntec
 * @since JDK1.6
 * 
 */
public class NearRealTimeTest extends TestCase {
	public void testNearRealTime() throws Exception {
		Directory dir = new RAMDirectory();
		IndexWriterConfig iwf = new IndexWriterConfig( Version.LUCENE_43, new StandardAnalyzer( Version.LUCENE_43 ) );
		IndexWriter writer = new IndexWriter( dir, iwf );

		for ( int i = 0; i < 10; i++ ) {
			Document doc = new Document();
			doc.add( new StringField( "id", "" + i, Field.Store.NO ) );
			doc.add( new TextField( "text", "aaa", Field.Store.NO ) );
			writer.addDocument( doc );
		}

		IndexReader reader = DirectoryReader.open( writer, true );
		IndexSearcher searcher = new IndexSearcher( reader );
		Query query = new TermQuery( new Term( "text", "aaa" ) );
		TopDocs docs = searcher.search( query, 1 );
		assertEquals( 10, docs.totalHits );

		writer.deleteDocuments( new Term( "id", "7" ) );

		Document doc = new Document();
		doc.add( new StringField( "id", "11", Field.Store.NO ) );
		doc.add( new TextField( "text", "bbb", Field.Store.NO ) );
		writer.addDocument( doc );

		// lucene3.x中的reopen已删除，使用下面方法替代，最后一个参数true为马上提交变化，false为不提交
		IndexReader newReader = DirectoryReader.openIfChanged( (DirectoryReader) reader, writer, true );
		assertFalse( newReader == reader );
		reader.close();

		searcher = new IndexSearcher( newReader );
		TopDocs hits = searcher.search( query, 10 );
		assertEquals( 9, hits.totalHits );
		query = new TermQuery( new Term( "text", "bbb" ) );
		hits = searcher.search( query, 1 );
		assertEquals( 1, hits.totalHits );

		newReader.close();
		writer.close();
		dir.close();
	}
}
